﻿using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;

namespace DexERP.Core.DBHelper
{
    public class OracleHelper
    {
        private string Oracleconstr { get; set; }
        private OracleConnection OracleCon { get; set; }
        private OracleDataAdapter Oracleodbadp { get; set; }
        private string OracleHost { get; set; }
        private string Oracle_UserID { get; set; }
        private string Oracle_Password { get; set; }
        private string Oracle_Port { get; set; }
        public OracleHelper(string host, string uid, string pwd, string port = "1521")
        {
            OracleHost = host;
            Oracle_UserID = uid;
            Oracle_Password = pwd;
            Oracle_Port = port;
            DBConnect();
        }
        /// <summary>
        /// 连接数据库，成功返回字符串success，失败返回错误信息
        /// </summary>
        /// <returns></returns>
        public string DBConnect()
        {
            try
            {
                Oracleconstr = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=" + OracleHost + ")(PORT=" + Oracle_Port + "))(CONNECT_DATA=(SERVICE_NAME=orcl.mixers.com.cn)));Persist Security Info=True;User ID=" + Oracle_UserID + ";Password=" + Oracle_Password + ";";
                OracleCon = new OracleConnection(Oracleconstr);

                if (OracleCon.State != ConnectionState.Open)
                {
                    OracleCon.Open();
                }
                return "success";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public DataTable Query(string sql, out string msg)
        {
            DataSet ds = new DataSet();
            DataTable t = new DataTable();
            try
            {
                Oracleodbadp = new OracleDataAdapter(sql, OracleCon);
                Oracleodbadp.Fill(ds, "a");
                t = ds.Tables["a"];
                msg = "success";
            }
            catch (Exception e) { msg = e.Message; }
            return t;
        }

        public void ConDispose()
        {
            if (OracleCon.State == ConnectionState.Open)
                OracleCon.Close();
            OracleCon = null;
        }
    }
}
